package edu.noteBook.utils;

import edu.noteBook.Pojo.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;
import java.util.Date;

public class JwtUtil {
    private static final SecretKey SECRET_KEY = Keys.secretKeyFor(SignatureAlgorithm.HS512);
    private static final long EXPIRATION_TIME = 86400000; // 1 day

    public static String generateToken(User user) {
        try {
//            System.out.println("开始生成token，用户ID: " + user.getId());
            String token = Jwts.builder()
                    .setSubject(user.getUsername())
                    .claim("id", user.getId())
                    .claim("username", user.getUsername())
                    .setIssuedAt(new Date())
                    .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
                    .signWith(SECRET_KEY, SignatureAlgorithm.HS512)
                    .compact();
//            System.out.println("生成的token: " + token);
            return token;
        } catch (Exception e) {
            System.out.println("生成token时发生错误: " + e.getMessage());
            e.printStackTrace();
            throw e;
        }
    }

    public static Claims parseToken(String token) {
        try {
//            System.out.println("开始解析token: " + token);

            if (token == null || token.trim().isEmpty()) {
                System.out.println("token为空");
                throw new IllegalArgumentException("Token is empty");
            }

            // 使用正确的 0.12.6 API
            return Jwts.parser()
                    .verifyWith(SECRET_KEY)  // 使用 verifyWith 替代 setSigningKey
                    .build()
                    .parseSignedClaims(token)  // 使用 parseSignedClaims 替代 parseClaimsJws
                    .getPayload();  // 使用 getPayload 替代 getBody

        } catch (io.jsonwebtoken.security.SecurityException e) {
            System.out.println("token签名验证失败: " + e.getMessage());
            throw e;
        } catch (io.jsonwebtoken.ExpiredJwtException e) {
            System.out.println("token已过期: " + e.getMessage());
            throw e;
        } catch (io.jsonwebtoken.MalformedJwtException e) {
            System.out.println("token格式错误: " + e.getMessage());
            throw e;
        } catch (io.jsonwebtoken.UnsupportedJwtException e) {
            System.out.println("不支持的token格式: " + e.getMessage());
            throw e;
        } catch (Exception e) {
            System.out.println("解析token时发生未知错误: " + e.getMessage());
            e.printStackTrace();
            throw e;
        }
    }

    public static boolean validateToken(String token) {
        try {
            parseToken(token);
            return true;
        } catch (Exception e) {
            System.out.println("token验证失败: " + e.getMessage());
            return false;
        }
    }
}

